//
//  KKStatusListViewModel.swift
//  SinaWeiBo
//
//  Created by King.Kong. on 16/5/27.
//  Copyright © 2016年 King.Kong. All rights reserved.
//

import UIKit

class KKStatusListViewModel: NSObject {
    // 定义模型数组
     lazy var statusViewModelArray: [KKStatusViewModel] = [KKStatusViewModel]()
//    lazy var statuses: [KKStatus] = [KKStatus]()
    
    func loadData(isPulling: Bool, finished: (isSuccess: Bool,count: Int) -> () ) {

        //数组的第一个元素的status.id
        //根据是否正在转动处理 since_id 和 max_id 为互斥参数
        var since_id: Int64 = 0
        var max_id: Int64 = 0
        
        if isPulling {
            max_id = statusViewModelArray.last?.status?.id ?? 0
        } else {
            since_id = statusViewModelArray.first?.status?.id ?? 0
        }

        KKNetworkTools.sharedTools.loadHomePageData(since_id,max_id: max_id) { (responseObject, error) in

            if error != nil {
                print(error)
//                SVProgressHUD.showWithStatus(AppErrorTip)
                finished(isSuccess: false,count: 0)
                return
            }
            // 请求成功
            //            print(responseObject)
            guard let dict = responseObject as? [String : AnyObject] else {
                finished(isSuccess: false,count: 0)
                return
            }
            
            guard let array = dict["statuses"] as? [[String : AnyObject]] else {
                finished(isSuccess: false,count: 0)
                return
            }
//            print(array)
            
            // 遍历数据 字典转模型
            var tempArray = [KKStatusViewModel]()
            for item in array {
                
                let status = KKStatus(dict: item)
                //在数组中添加视图模型
                //TODO:
                let viewmodel = KKStatusViewModel(status: status)
                tempArray.append(viewmodel)
            }
//            self.statusViewModelArray = tempArray
//            self.statusViewModelArray = tempArray + self.statusViewModelArray

            if isPulling {
                //加载更多数据
                self.statusViewModelArray = self.statusViewModelArray + tempArray
            } else {
                //刷新新数据
                self.statusViewModelArray = tempArray + self.statusViewModelArray
            }

//            self.tableView.reloadData()
            finished(isSuccess: true,count: tempArray.count)

        }
        
    }
    

}
